package org.example.logindemo.service.impl;

import org.example.logindemo.domain.ResponseResult;
import org.example.logindemo.domain.entity.User;
import org.example.logindemo.enums.AppHttpCodeEnum;
import org.example.logindemo.service.LoginService;
import org.example.logindemo.utils.JwtUtil;
import org.example.logindemo.utils.RedisCache;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {

    private static Map<String, String> userMap = new HashMap<>();
    static {
        userMap.put("Tom", "123456");
    }

    @Resource
    private RedisCache redisCache;

    public LoginServiceImpl(RedisCache redisCache){
        this.redisCache = redisCache;
    }

    @Override
    public ResponseResult login(User user) {

        // 身份校验
        String cachedPwd = userMap.get(user.getUser());
        if(null != cachedPwd && cachedPwd.equals(user.getPassword())){
            // 生成token
            String userName = user.getUser();
            String jwt = JwtUtil.createJWT(userName);
            // 信息存入redis
            redisCache.setCacheObject("login:" + userName, user);
            // 返回token
            Map<String, String> result = new HashMap<>();
            result.put("auth_token", jwt);
            return ResponseResult.okResult(result);
        }

        return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR);
    }

    @Override
    public ResponseResult logout() {
        return null;
    }
}
